<?php
require_once(__DIR__.'/wechat/Wx.class.php');

/**
 * Created by PhpStorm.
 * User: jingx
 * Date: 2017/6/18
 * Time: 18:10
 */
class WeChatApp extends TPWechat
{
    public static $instance;

    static public function instance()
    {
        $options = [
            'token' => 'gyvFBzIYXQVUiDdJfG1E',
            'appid' => 'wx93def4a03e34d90b',
            'appsecret' => 'adc615d32224d156d13109557a6078de',
            'encodingaeskey' => '7P8Xq0xURzVidmwlRE9fd2Q5BhVPhcOwHzBujLPwnXk',
        ];

        if (!self::$instance) {
            self::$instance = new self($options);
        }

        return self::$instance;
    }

    public function response()
    {
        $this->valid();
        $type = $this->getRev()->getRevType();
        switch ($type) {
            case Wechat::MSGTYPE_TEXT:
                $this->responseText();
                break;
            case Wechat::MSGTYPE_EVENT:
                $this->responseEvent();
                break;
            case Wechat::MSGTYPE_IMAGE:
                $this->responseImage();
                break;
            default:
                $this->text("help info")->reply();
        }
    }

    protected function responseText()
    {
        $this->text("hello, I'm wechat")->reply();
    }

    protected function responseEvent()
    {
        $revData = $this->getRevData();
        switch ($revData['Event']) {
            case Wechat::EVENT_SUBSCRIBE:
                /** @var JfUserModel $model */
                $model = D('JfUser');
                $model->relatedUser($revData['FromUserName'], $revData['ToUserName']);
                break;
            case Wechat::EVENT_MENU_CLICK:
                /** @var UserActivityModel $userActivity */
                $userActivity = D('UserActivity');
                $userActivity->joinActivity($revData['EventKey'], $revData['FromUserName'])->replyPost();
                break;
            default:
        }
    }

    protected function responseImage()
    {
        $this->text('看不懂这张图片是什么耶')->reply();
    }
}